﻿
using Janus.BaseEntitys;
using Janus.Cores.Tools;
using Janus.Mes.Services.Interface;
using Janus.Mes.VO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;
using System.Web.UI;


namespace Janus.Mes.WebClient
{
    public static partial class MyHtmlHelper
    {
        #region 自定义控件
        public static HtmlString GenerateLeftMenu(List<ModuleDTO> roles, List<ModuleDTO> sourceRoles, int deep)
        {
            string header = "<ul {1}>{0}</ul>";
            string itemstr = "<li><a class='{2}' href='{0}{7}' target='{1}' rel='{2}' fresh='{3}' External='{4}' isRefresh='{8}'>{5}</a>{6}</li>";
            string headerclass = string.Empty;
            headerclass = deep > 1 ? string.Empty : "class=\"tree treeFolder\"";
            string result = string.Empty;
            foreach (var m in roles.OrderBy(c => c.Order))
            {
                string rel = m.ID;
                string opid = "";
                if (!string.IsNullOrEmpty(m.Url) && m.Url.IndexOf("OpID", StringComparison.InvariantCultureIgnoreCase) < 1)
                {
                    opid = (m.Url.IndexOf("?") > 0 ? "&" : "?") + "OpID=" + m.ID;
                }
                rel = (rel ?? "Default").ToLower();
                result += string.Format(itemstr,
                    m.Url,
                    m.Target,
                    rel,
                    !string.IsNullOrEmpty(m.Fresh) ? m.Fresh.ToLower() : "",
                    !string.IsNullOrEmpty(m.External) ? m.External.ToLower() : "",
                    m.ModuleName,
                    GenerateLeftMenu(sourceRoles.Where(c => !string.IsNullOrEmpty(m.ID) && c.Parent == m.ID && c.Types == 0).ToList(), sourceRoles, deep + 1),
                    opid,
                    m.IsRefresh);
            }
            if (!string.IsNullOrEmpty(result))
            {
                result = string.Format(header, result, headerclass);
            }
            return new HtmlString(result);

        }

        /// <summary>
        /// htmlAttribute:扩展属性如下
        ///selectedvalue            选中值
        ///filter="id,orgName"      需要过滤的列名
        ///filttype="or"            过滤的模式{and 或 or}
        ///ajax=""                  从后台异步请求数据
        ///datavalue="id:序号"      绑定value列
        ///datatext="orgName:部门"  绑定Text列
        ///columns='[{orgNum:"部门编码",parent:"上司"}]' 其他列
        ///ref =                    联动下级
        ///refUrl =                 联动下级异步请求后台数据
        ///noValue                  不显示值列
        ///dtid =                   呈现树状时当前ID
        ///dtpid =                  呈现树状时父ID
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="htmlHelper"></param>
        /// <param name="source"></param>
        /// <param name="htmlAttributes"></param>
        /// <returns></returns>
        public static MvcHtmlString Select<T>(this HtmlHelper htmlHelper, IEnumerable<T> source, object htmlAttribute = null)
        {
            source = source ?? new List<T>();
            var htmlAttributes = htmlAttribute is RouteValueDictionary ? htmlAttribute as RouteValueDictionary : HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttribute);

            var selecter = "<select id=\"{0}\" name=\"{1}\"  {2}>{3}</select>\r\n";
            var option = "<option value=\"{0}\" {2}=\"{3}\"  {4}=\"{5}\" other=\"[{6}]\" {7} {8}>{1}</option>\r\n";
            string html = string.Empty;
            string htmlOption = "<option value=\"\">" + HelperCommon.SelectDefaultValue + "</option>\r\n";

            if (htmlAttributes != null)
            {
                #region 取出html属性
                var igoreCol = new List<string>() { "Count", "Keys", "Values" };
                var attributes = string.Join(" ", htmlAttributes.Select(c => { if (!igoreCol.Contains(c.Key)) { return string.Format("{0}=\"{1}\"", c.Key, c.Value); } return null; }));
                #endregion
                string datavalue = htmlAttributes["datavalue"] as string;
                //绑定值
                string valcol = string.Empty;
                if (!string.IsNullOrEmpty(datavalue))
                {
                    valcol = datavalue.Split(':')[0];
                }
                string datatext = htmlAttributes["datatext"] as string;
                //绑定列名
                string textcol = string.Empty;
                if (!string.IsNullOrEmpty(datatext))
                { textcol = datatext.Split(':')[0]; }
                //选定值
                string selected = htmlAttributes["selectedvalue"] as string;
                //其他列
                string columnObjs = htmlAttributes["columns"] as string;
                Regex regex = new Regex(@"\w+:");
                List<string> columns = new List<string>();
                if (!string.IsNullOrEmpty(columnObjs))
                {
                    var regResult = regex.Matches(columnObjs);
                    if (regResult.Count > 0)
                    {
                        for (int i = 0; i < regResult.Count; i++)
                        {
                            columns.Add(regResult[i].Value.Replace(":", ""));
                        }
                    }

                }
                string columnsStr = string.Empty;
                foreach (var item in source)
                {
                    columnsStr = string.Empty;
                    if (columns.Count > 0)
                    {

                        var columnsList = columns.Select(c =>
                        {
                            string cVal = RelfHelper.GetValue(item, c) as string;
                            if (!string.IsNullOrEmpty(cVal))
                            { cVal = cVal.Replace("\r", "").Replace("\n", ""); }
                            return string.Format("{0}:'{1}'", c, cVal);
                        });
                        columnsStr += string.Join(",", columnsList);
                    }
                    string textv = string.Empty;
                    if (!string.IsNullOrEmpty(textcol))
                    {
                        var tobj = RelfHelper.GetValue(item, textcol);
                        textv = tobj != null ? tobj.ToString() : "";
                    }
                    if (!string.IsNullOrEmpty(textv))
                    {
                        textv = textv.Replace("\"", "”").Replace("\r", "").Replace("\n", "");
                    }
                    var vobj = RelfHelper.GetValue(item, valcol);
                    string val = vobj != null ? vobj.ToString() : "";
                    //<option value=\"{0}\" {2}=\"{3}\"  {4}=\"{5}\" other=\"[{6}]\">{1}</option>\r\n
                    string str8 = string.Empty;
                    string dtid = htmlAttributes["dtid"] as string;
                    string dtpid = htmlAttributes["dtpid"] as string ?? "";
                    if (dtid != null)
                    {
                        str8 = string.Format("data-tt-id=\"{0}\" data-tt-parent-id=\"{1}\"", RelfHelper.GetValue(item, dtid), RelfHelper.GetValue(item, dtpid));
                    }
                    htmlOption += string.Format(option,
                        htmlHelper.Encode(val),
                        textv,
                        valcol,
                        htmlHelper.Encode(RelfHelper.GetValue(item, valcol)),
                        textcol,
                        textv,
                        htmlHelper.Encode("{" + columnsStr + "}"),
                        selected == val ? "selected" : "",
                        str8
                        );
                }
                string name = (htmlAttributes["name"] as string) ?? typeof(T).Name; ;
                string id = (htmlAttributes["id"] as string) ?? (name ?? typeof(T).Name); ;

                html = string.Format(selecter,
                   id.Replace("[", "_").Replace("]", "_").Replace("-", "_").Replace(".", "_"),
                   name,
                   attributes,
                   htmlOption
                    );
            }
            return MvcHtmlString.Create(html);
        }
        /// <summary>
        /// 检验特性_检验项目编码
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="htmlAttribute"></param>
        /// <returns></returns>
        public static MvcHtmlString SelectCheckProject(this HtmlHelper htmlHelper, object htmlAttribute = null)
        {
            ICheckProject CheckProjectServices = ServiceFactory.Create<ICheckProject>();
            var lstCheckDTO = CheckProjectServices.FindAll(new Querier());
            List<CheckProjectVO> lstCheckVO = new List<CheckProjectVO>();
            if (lstCheckDTO != null)
            {
                lstCheckVO = AutoMapper.Mapper.DynamicMap<List<CheckProjectVO>>(lstCheckDTO);
            }

            var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttribute);
            RouteValueDictionary hAttribute = new RouteValueDictionary(htmlAttribute);
            if (hAttribute.ContainsKey("class"))
            {
                hAttribute["class"] = hAttribute["class"] + " select3";
            }
            else
            {
                hAttribute.Add("class", "select3");
            }
            if (!hAttribute.ContainsKey("datatext"))
                hAttribute.Add("datatext", "CheckPName:检验项目");
            if (!hAttribute.ContainsKey("datavalue")) 
                hAttribute.Add("datavalue", "CheckPCode:检验项目编码"); 
            //if (!hAttribute.ContainsKey("columns"))
            //    hAttribute.Add("columns", "[{UserID:'账号',OrgName:'组织',Tel:'电话'}]");

            var result = htmlHelper.Select<CheckProjectVO>(lstCheckVO ?? new List<CheckProjectVO>(), hAttribute);
            return result;
        }
        /// <summary>
        /// 检验特性_缺陷等级
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="htmlAttribute"></param>
        /// <returns></returns>
        public static MvcHtmlString SelectDefectLName(this HtmlHelper htmlHelper, object htmlAttribute = null)
        {
            IDefectLevel DefectLevelServices = ServiceFactory.Create<IDefectLevel>();
            var lstDefectLDTO = DefectLevelServices.FindAll(new Querier());
            List<DefectLevelVO> lstDefectLVO = new List<DefectLevelVO>();
            if (lstDefectLDTO != null)
            {
                lstDefectLVO = AutoMapper.Mapper.DynamicMap<List<DefectLevelVO>>(lstDefectLDTO);
            }

            var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttribute);
            RouteValueDictionary hAttribute = new RouteValueDictionary(htmlAttribute);
            if (hAttribute.ContainsKey("class"))
            {
                hAttribute["class"] = hAttribute["class"] + " select3";
            }
            else
            {
                hAttribute.Add("class", "select3");
            }
            if (!hAttribute.ContainsKey("datavalue"))
                hAttribute.Add("datavalue", "DefectLCode:缺陷等级");
            if (!hAttribute.ContainsKey("datatext"))
                hAttribute.Add("datatext", "DefectLName:等级名称");
            var result = htmlHelper.Select<DefectLevelVO>(lstDefectLVO ?? new List<DefectLevelVO>(), hAttribute);
            return result;
        }
        /*
        /// <summary>
        /// 部门控件
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="htmlAttribute"></param>
        /// <returns></returns>
        public static MvcHtmlString SelectDepartment(this HtmlHelper htmlHelper, object htmlAttribute = null)
        {
            IOrganization departmentService = ServiceFactory.CreateServiceE<IOrganization>();
            var deptList = departmentService.FindAll();
            var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttribute);
            RouteValueDictionary hAttribute = new RouteValueDictionary(htmlAttribute);
            if (hAttribute.ContainsKey("class"))
            {
                hAttribute["class"] = hAttribute["class"] + " select3";
            }
            else
            {
                hAttribute.Add("class", "select3");
            }
            hAttribute.Add("datavalue", "Code:编码");
            hAttribute.Add("datatext", "Name:部门名称");
            hAttribute.Add("columns", "[{Remark:'备注'}]");
            hAttribute.Add("dtid", "Code");
            hAttribute.Add("dtpid", "ParentID");

            var result = htmlHelper.Select<Organization>(deptList, hAttribute);
            return result;
        }

        [OutputCache(Duration = 120, Location = OutputCacheLocation.ServerAndClient)]
        public static MvcHtmlString TreeDepartment(this HtmlHelper htmlHelper, object htmlAttribute = null)
        {
            string html = string.Empty;
            string ul = "<ul class=\"tree treeFolder\">\r\n{0}\r\n</ul>";
            string li = "<li><a href=\"{0}\" target=\"{1}\" rel=\"{2}\" title='员工管理'>{3}</a>\r\n{4}</li>";
            string subClass = string.Empty;
            string header = string.Empty;

            var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttribute);
            RouteValueDictionary hAttribute = new RouteValueDictionary(htmlAttribute);
            IOrganization departmentService = ServiceFactory.CreateServiceE<IOrganization>();
            var deptList = departmentService.FindAll();
            hAttribute["target"] = hAttribute["target"] ?? "navTab";
            hAttribute["rel"] = hAttribute["rel"] ?? "system_employes";

            header = string.Format(li
                  , hAttribute["url"] ?? "System/Employes/index?action=search&OpID=System_Employes&OrgID="
                  , hAttribute["target"]
                  , hAttribute["rel"]
                  , "所有部门"
                  , "{0}"
                  );
            header = string.Format(ul, header);
            string subhtml = GetSubDepartment(deptList, null, hAttribute);
            html = string.Format(header, subhtml);
            return MvcHtmlString.Create(html);
        }

        private static string GetSubDepartment(List<Organization> source, string pID, RouteValueDictionary hAttribute)
        {
            string html = string.Empty;
            string ul = "<ul>\r\n{0}\r\n</ul>\r\n";
            string li = "<li class=\"{5}\"><a href=\"{0}\" target=\"{1}\" rel=\"{2}\" title='员工管理'>{3}</a>{4}</li>\r\n";

            var list = string.IsNullOrEmpty(pID) ? source.Where(c => string.IsNullOrEmpty(c.ParentID)).OrderBy(c => c.Code).ToList()
                                               : source.Where(c => c.ParentID == pID).OrderBy(c => c.Code).ToList();
            //无数据返回
            if (list.Count <= 0) return string.Empty;
            string selected = hAttribute["selected"] as string;
            list.ForEach(c =>
            {

                html += string.Format(li
                    , (hAttribute["url"] ?? "System/Employes/index?action=search&OpID=System_Employes&OrgID=") + c.Code
                    , hAttribute["target"]
                    , hAttribute["rel"]
                    , c.Name
                    , !string.IsNullOrEmpty(c.Code) ? GetSubDepartment(source, c.Code, hAttribute) : ""
                    , selected == c.Code ? "selected" : ""
                    );
            });
            if (!string.IsNullOrEmpty(html))
            {
                html = string.Format(ul, html);
            }

            return html;
        }

        /// <summary>
        /// 用户单选
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="htmlAttribute"></param>
        /// <returns></returns>
        public static MvcHtmlString SelectUsers(this HtmlHelper htmlHelper, object htmlAttribute = null)
        {
            IUsers usersService = ServiceFactory.CreateServiceE<IUsers>();
            var estateList = usersService.FindAll();
            var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttribute);
            RouteValueDictionary hAttribute = new RouteValueDictionary(htmlAttribute);
            if (hAttribute.ContainsKey("class"))
            {
                hAttribute["class"] = hAttribute["class"] + " select3";
            }
            else
            {
                hAttribute.Add("class", "select3");
            }
            if (!hAttribute.ContainsKey("datavalue"))
            {
                hAttribute.Add("datavalue", "UserID:ID");
            }
            if (!hAttribute.ContainsKey("datatext"))
            {
                hAttribute.Add("datatext", "UserID:用户账号");
            }
            if (!hAttribute.ContainsKey("columns"))
            {
                hAttribute.Add("columns", "[{Tel:'电话',Email:'邮箱'}]");
            }
            var result = htmlHelper.Select<UsersDSC>(estateList, hAttribute);
            return result;
        }

        /// <summary>
        /// 楼盘选择
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="htmlAttribute"></param>
        /// <returns></returns>
        public static MvcHtmlString SelectEstate(this HtmlHelper htmlHelper, object htmlAttribute = null)
        {
            IEstate estateService = ServiceFactory.CreateServiceE<IEstate>();
            var estateList = estateService.FindAll();
            var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttribute);
            RouteValueDictionary hAttribute = new RouteValueDictionary(htmlAttribute);
            if (hAttribute.ContainsKey("class"))
            {
                hAttribute["class"] = hAttribute["class"] + " select3";
            }
            else
            {
                hAttribute.Add("class", "select3");
            }
            if (!hAttribute.ContainsKey("noValue"))
                hAttribute.Add("noValue", "true");
            if (!hAttribute.ContainsKey("datavalue"))
                hAttribute.Add("datavalue", "SId:编码");
            if (!hAttribute.ContainsKey("datatext"))
                hAttribute.Add("datatext", "Name:楼盘名称");
            if (!hAttribute.ContainsKey("columns"))
                hAttribute.Add("columns", "[{PinYin:'拼音码'}]");
            if (!hAttribute.ContainsKey("filter"))
                hAttribute.Add("filter", "Name,PinYin");



            var result = htmlHelper.Select<EstateDSC>(estateList, hAttribute);
            return result;
        }

        

        /// <summary>
        /// 员工单选
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="htmlAttribute"></param>
        /// <returns></returns>
        public static MvcHtmlString SelectEmployes(this HtmlHelper htmlHelper, object htmlAttribute = null)
        {
            IEmployes employesService = ServiceFactory.CreateServiceE<IEmployes>();
            var employes = employesService.FindAll();
            var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttribute);
            RouteValueDictionary hAttribute = new RouteValueDictionary(htmlAttribute);
            if (hAttribute.ContainsKey("class"))
            {
                hAttribute["class"] = hAttribute["class"] + " select3";
            }
            else
            {
                hAttribute.Add("class", "select3");
            }
            if (!hAttribute.ContainsKey("datavalue"))
                hAttribute.Add("datavalue", "UserCode:编码");
            if (!hAttribute.ContainsKey("datatext"))
                hAttribute.Add("datatext", "UserName:名称");
            if (!hAttribute.ContainsKey("columns"))
                hAttribute.Add("columns", "[{UserID:'账号',OrgName:'组织',Tel:'电话'}]");

            var result = htmlHelper.Select<EmployesDSC>(employes, hAttribute);
            return result;
        }

        /// <summary>
        /// 员工多选
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="lookupgroup"></param>
        /// <param name="selected"></param>
        /// <param name="htmlAttribute"></param>
        /// <returns></returns>
        public static MvcHtmlString SelectMutilEmployes(this HtmlHelper htmlHelper, string lookupgroup, List<EmployesDSC> selected = null, object htmlAttribute = null)
        {
            var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttribute);
            RouteValueDictionary hAttribute = new RouteValueDictionary(htmlAttribute);
            if (hAttribute.ContainsKey("class"))
            {
                hAttribute["class"] = hAttribute["class"] + " toMutil";
            }
            else
            {
                hAttribute.Add("class", "toMutil");
            }
            string post = string.Empty;
            Dictionary<string, string> columns = new Dictionary<string, string>();
            columns.Add("UserCode", "");
            columns.Add("UserName", "");
            columns.Add("UserID", "");
            columns.Add("OrgName", "");
            columns.Add("Tel", "");

            if (selected != null)
            {
                hAttribute["selected"] = string.Join(",", selected.Select(c => c.UserName));
                columns["UserCode"] = string.Join(",", selected.Select(c => c.UserCode));
                columns["UserName"] = hAttribute["selected"].ToString();
                columns["UserID"] = string.Join(",", selected.Select(c => c.UserID));
                columns["OrgName"] = string.Join(",", selected.Select(c => c.OrgName));
                columns["Tel"] = string.Join(",", selected.Select(c => c.Tel));
            }
            return SelectMutil(htmlHelper, "UserName", "System/Employes/SelectEmployes?selected={" + lookupgroup + "_UserCode}", lookupgroup, columns, "选择员工", hAttribute);
        }

        /// <summary>
        /// 扩展的DropDownList
        /// 用来获取数据字典里的参数
        /// 第一项默认为“请选择”
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="GroupName">数据字典名称</param>
        /// <param name="selectIndex">选择项下标，从0开始，默认为0</param>
        /// <param name="htmlAttributes">样式</param>
        /// <returns></returns>
        public static MvcHtmlString SelectSysDictionary(this HtmlHelper htmlHelper, string GroupName, object htmlAttribute = null)
        {
            IBSysDictionary sysDictionaryService = ServiceFactory.CreateServiceE<IBSysDictionary>();
            var payTypes = sysDictionaryService.GetByCache(string.Format("GroupName = \"{0}\"", GroupName)) ?? new BaseSysDictionaryDSC();
            var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttribute);
            RouteValueDictionary hAttribute = new RouteValueDictionary(htmlAttribute);
            if (hAttribute.ContainsKey("class"))
            {
                hAttribute["class"] = hAttribute["class"] + " selectToCols";
            }
            else
            {
                hAttribute.Add("class", "selectToCols");
            }
            hAttribute.Add("datavalue", "GKey:编码");
            hAttribute.Add("datatext", "Value:值");
            hAttribute.Add("columns", "[{GroupName:'分组名'},{Order:'排序'},{GKey:'主健'}]");
            var result = htmlHelper.Select<SysDictionaryDSC>(payTypes.SubDictionary, hAttribute);
            return result;
        }

        /// <summary>
        /// 数据字典复选框（配合checkboxToCols）
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="GroupName"></param>
        /// <param name="prefix"></param>
        /// <param name="selected"></param>
        /// <param name="htmlAttribute"></param>
        /// <returns></returns>
        public static MvcHtmlString CheckListSysDictionary(this HtmlHelper htmlHelper, string GroupName, string prefix, List<SysDictionaryDSC> selected = null, object htmlAttribute = null)
        {
            string html = string.Empty;
            string checkboxHtm = "<span class=\"checkbox\"><input type=\"checkbox\" id='{4}' name='{4}' columns=\"[{2}]\" prefix=\"{3}\" {0}  {5} />{1}</span>\r\n";
            var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttribute);
            RouteValueDictionary hAttribute = new RouteValueDictionary(htmlAttribute);
            string attr = string.Empty;
            foreach (var item in hAttribute)
            {
                if (!string.IsNullOrEmpty(item.Key))
                {
                    attr += string.Format(" {0}='{1}'", item.Key, item.Value);
                }
            }
            IBSysDictionary sysDictionaryService = ServiceFactory.CreateServiceE<IBSysDictionary>();
            var sysDic = sysDictionaryService.GetByCache(string.Format("GroupName = \"{0}\"", GroupName)) ?? new BaseSysDictionaryDSC();
            if (sysDic != null && sysDic.SubDictionary != null)
            {
                int i = 1;
                sysDic.SubDictionary.ForEach(c =>
                {
                    string ischeck = string.Empty;
                    if (selected != null)
                    {
                        ischeck = selected.FirstOrDefault(k => k.GKey == c.GKey) != null ? "checked" : "";
                    }
                    string columns = "{" + string.Format("GKey:'{0}',Value:'{1}',GroupName:'{2}',Order:'{3}',Key:'{4}'",
                                                    c.GKey, c.Value, c.GroupName, c.Order, c.Key) + "}";
                    html += string.Format(checkboxHtm, attr, c.Value, columns, prefix, prefix + i.ToString(), ischeck);
                    i += 1;
                });
            }
            html = string.Format(" <span class=\"checkboxToCols\" id=\"{1}\">{0}</span>", html, prefix);
            return MvcHtmlString.Create(html);
        }

        /// <summary>
        /// 公司多选
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="lookupgroup"></param>
        /// <param name="selected"></param>
        /// <param name="htmlAttribute"></param>
        /// <returns></returns>
        public static MvcHtmlString SelectMutilCompany(this HtmlHelper htmlHelper, string lookupgroup, List<CompanyDSC> companyList, List<string> selected = null, object htmlAttribute = null)
        {
            string companyIDs = string.Empty;
            companyList = companyList ?? new List<CompanyDSC>();
            var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttribute);
            RouteValueDictionary hAttribute = new RouteValueDictionary(htmlAttribute);
            if (hAttribute.ContainsKey("class"))
            {
                hAttribute["class"] = hAttribute["class"] + " toMutil";
            }
            else
            {
                hAttribute.Add("class", "toMutil");
            }
            string post = string.Empty;
            Dictionary<string, string> columns = new Dictionary<string, string>();
            columns.Add("SId", "");
            columns.Add("Name", "");
            columns.Add("FullName", "");

            if (selected != null)
            {
                List<string> companyNames = companyList.Where(c => selected.Contains(c.SId)).Select(c => c.Name).ToList();
                List<string> companyFullNames = companyList.Where(c => selected.Contains(c.SId)).Select(c => c.FullName).ToList();
                hAttribute["selected"] = string.Join(",", companyNames);
                columns["SId"] = string.Join(",", selected);
                columns["Name"] = hAttribute["selected"].ToString();
                columns["FullName"] = string.Join(",", companyFullNames);

                List<string> lstCompanyIDs = companyList.Where(c => selected.Contains(c.SId)).Select(c => c.CompanyID).ToList();
                companyIDs = string.Join(",", lstCompanyIDs);
            }
            return SelectMutil(htmlHelper, "Name", "System/Company/SelectCompany?selected=" + companyIDs, lookupgroup, columns, "选择分销商", hAttribute);
        }

        /// <summary>
        /// 多选（配合toMutil)
        /// <param name="htmlHelper"></param>
        /// <param name="name">指定显示的名称</param>
        /// <param name="targetUrl">选择数据地址</param>
        /// <param name="lookupgroup">分组名</param>
        /// <param name="columns">需要提交的字段 key:字段名 value:默认值</param>
        /// <param name="htmlAttribute">
        /// suggestfields:联动提交字段
        /// postfield:提交字段
        /// suggesturl:联动地址
        /// </param>
        /// <returns></returns>
        public static MvcHtmlString SelectMutil(this HtmlHelper htmlHelper, string name, string targetUrl, string lookupgroup, Dictionary<string, string> columns, string title = "查找带回", object htmlAttribute = null)
        {
            var htmlAttributes = htmlAttribute is RouteValueDictionary ? htmlAttribute as RouteValueDictionary : HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttribute);

            string html = "<input name=\"{0}\" class=\"{1}\" type=\"text\" readonly='true' value='" + htmlAttributes["selected"] + "'{4}/>\r\n"
                              + "<a class='btnLook' href=\"{2}\" lookupgroup=\"{3}\" rel='{6}'>" + title + "</a>\r\n{5}";

            string otherAttribute = string.Empty;
            string toMutil = string.Empty;
            foreach (var item in htmlAttributes)
            {
                if (!item.Key.Contains("class"))
                {
                    otherAttribute += string.Format(" {0}='{1}'", item.Key, item.Value);
                }
                else
                {
                    toMutil = item.Value.ToString().Contains("toMutil") ? "toMutil" : null;
                }
            }
            string input = "<input class=\"" + toMutil + "\" name=\"{0}\" id='{1}' value=\"{2}\" type=\"hidden\" />\r\n";
            string htmlinput = string.Empty;
            foreach (var s in columns)
            {
                if (s.Key != name)
                {
                    string iName = lookupgroup + "." + s.Key;
                    htmlinput += string.Format(input, iName, iName.Replace(".", "_"), s.Value);
                }
            }

            html = string.Format(html,
                lookupgroup + "." + name
                , htmlAttributes["class"]
                , targetUrl
                , lookupgroup
                , otherAttribute
                , htmlinput
                , htmlAttributes["rel"]
                );
            return MvcHtmlString.Create(html);
        }
        */
        /// <summary>
        /// 职务单选控件
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="htmlAttribute"></param>
        /// <returns></returns>
        public static MvcHtmlString SelectRolers(this HtmlHelper htmlHelper, object htmlAttribute = null)
        {
            //IRolers rolersService = ServiceFactory.CreateServiceE<IRolers>();
            //var deptList = rolersService.FindAll();
            var rolers = new List<RolersVO>();
            rolers.Add(new RolersVO() { Name = "test1", Code = "0001", ParentID = "0" });
            rolers.Add(new RolersVO() { Name = "test00010001", Code = "00010001", ParentID = "0001" });
            rolers.Add(new RolersVO() { Name = "test00010002", Code = "00010002", ParentID = "0001" });
            rolers.Add(new RolersVO() { Name = "test2", Code = "0002", ParentID = "0" });
            rolers.Add(new RolersVO() { Name = "test00020001", Code = "00020001", ParentID = "0002" });

            var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttribute);
            RouteValueDictionary hAttribute = new RouteValueDictionary(htmlAttribute);
            if (hAttribute.ContainsKey("class"))
            {
                hAttribute["class"] = hAttribute["class"] + " select3";
            }
            else
            {
                hAttribute.Add("class", "select3");
            }
            if (!hAttribute.ContainsKey("datavalue"))
                hAttribute.Add("datavalue", "Code:编码");
            if (!hAttribute.ContainsKey("datatext"))
                hAttribute.Add("datatext", "Name:名称");
            if (!hAttribute.ContainsKey("dtid"))
                hAttribute.Add("dtid", "Code");
            if (!hAttribute.ContainsKey("dtpid"))
                hAttribute.Add("dtpid", "ParentID");
            if (!hAttribute.ContainsKey("columns"))
                hAttribute.Add("columns", "[{Remark:'备注'}]");

            var result = htmlHelper.Select<RolersVO>(rolers, hAttribute);
            return result;
        }

        /// <summary>
        /// 职务多选
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="htmlAttribute"></param>
        /// <returns></returns>
        //public static MvcHtmlString SelectMutilRolers(this HtmlHelper htmlHelper, string lookupgroup, List<RolersVO> selected = null, object htmlAttribute = null)
        //{
        //    var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttribute);
        //    RouteValueDictionary hAttribute = new RouteValueDictionary(htmlAttribute);
        //    if (hAttribute.ContainsKey("class"))
        //    {
        //        hAttribute["class"] = hAttribute["class"] + " toMutil";
        //    }
        //    else
        //    {
        //        hAttribute.Add("class", "toMutil");
        //    }
        //    string post = string.Empty;
        //    Dictionary<string, string> columns = new Dictionary<string, string>();
        //    columns.Add("Code", "");
        //    columns.Add("Name", "");
        //    if (selected != null)
        //    {
        //        hAttribute["selected"] = string.Join(",", selected.Select(c => c.Name));
        //        post = string.Join(",", selected.Select(c => c.Code));
        //        columns["Code"] = post;
        //        columns["Name"] = hAttribute["selected"].ToString();
        //    }
        //    return SelectMutil(htmlHelper, "Name", "System/Rolers/SelectRolers?selected={" + lookupgroup + "_Code}", lookupgroup, columns, "选择职务", hAttribute);
        //}
        #endregion


        /// <summary>
        /// 物料单选（仅供静态界面使用）
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="htmlAttribute"></param>
        /// <returns></returns>
        public static MvcHtmlString SelectMaterial(this HtmlHelper htmlHelper, object htmlAttribute = null)
        {
            //IRolers rolersService = ServiceFactory.CreateServiceE<IRolers>();
            //var deptList = rolersService.FindAll();
            var rolers = new List<RolersVO>();
            rolers.Add(new RolersVO() { Name = "02K407A14M", Code = "WI000001", Remark = "A", OperDept = "WB16010001", Creator = "001", Updater = "XXXXX", CreatorCode = "下料作业工艺第一版", UpdaterCode = "CNC1" });
            rolers.Add(new RolersVO() { Name = "02K407A24M", Code = "WI000002", Remark = "A", OperDept = "WB16010001", Creator = "001", Updater = "XXXXX", CreatorCode = "下料作业工艺第二版", UpdaterCode = "CNC2" });
            rolers.Add(new RolersVO() { Name = "03K407A34M", Code = "WI000003", Remark = "A", OperDept = "WB16010001", Creator = "001", Updater = "XXXXX", CreatorCode = "下料作业工艺第三版", UpdaterCode = "CNC3" });
            rolers.Add(new RolersVO() { Name = "04K407A44M", Code = "WI000004", Remark = "A", OperDept = "WB16010001", Creator = "001", Updater = "XXXXX", CreatorCode = "下料作业工艺第四版", UpdaterCode = "CNC4" });
            rolers.Add(new RolersVO() { Name = "05K407A54M", Code = "WI000005", Remark = "A", OperDept = "WB16010001", Creator = "001", Updater = "XXXXX", CreatorCode = "下料作业工艺第五版", UpdaterCode = "CNC5" });

            var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttribute);
            RouteValueDictionary hAttribute = new RouteValueDictionary(htmlAttribute);
            if (hAttribute.ContainsKey("class"))
            {
                hAttribute["class"] = hAttribute["class"] + " select3";
            }
            else
            {
                hAttribute.Add("class", "select3");
            }
            if (!hAttribute.ContainsKey("datavalue"))
                hAttribute.Add("datavalue", "Code:料号");
            if (!hAttribute.ContainsKey("datatext"))
                hAttribute.Add("datatext", "Name:工艺路线");
            if (!hAttribute.ContainsKey("dtid"))
                hAttribute.Add("dtid", "Code");
            if (!hAttribute.ContainsKey("dtpid"))
                hAttribute.Add("dtpid", "ParentID");

            if (!hAttribute.ContainsKey("columns"))
                hAttribute.Add("columns", "[{Remark:'工艺版本'},{OperDept:'工序代码'},{Creator:'工序编号'},{Updater:'品名规格'},{CreatorCode:'工艺路线描述'},{UpdaterCode:'工序描述'}]");

            var result = htmlHelper.Select<RolersVO>(rolers, hAttribute);
            return result;
        }

    }
}